/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.wpi.first.wpilibj.templates.commands;

import edu.wpi.first.wpilibj.networktables.NetworkTable;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;


public class FlywheelPIDuserset extends CommandBase {

    private NetworkTable preferencesTable;
    private double usertarget;

    public FlywheelPIDuserset() {
        // Use requires() here to declare subsystem dependencies
        // eg. requires(chassis);
        requires(flyPID);

        preferencesTable = NetworkTable.getTable("Preferences");
        preferencesTable.putString("Enter Flyrate then TAB key", "0.0");
    }

    // Called just before this Command runs the first time
    protected void initialize() {
        flyPID.reset();
        flyPID.zerohall();
        flyPID.zerospeed();
        readtablespeed();
        flyPID.setSetpoint(usertarget);
        //SmartDashboard.putDouble("targetRPM = ", usertarget);
        flyPID.enable();
    }

    // Called repeatedly when this Command is scheduled to run
    protected void execute() {
        readtablespeed();
        flyPID.setSetpoint(usertarget);
        //SmartDashboard.putDouble("targetRPM = ", usertarget);
    }

    // Make this return true when this Command no longer needs to run execute()
    protected boolean isFinished() {
        //getPosition returns PID input value (current speed)
        return Math.abs(flyPID.getPosition() - usertarget) == 0;
    }

    // Called once after isFinished returns true
    protected void end() {
        if (usertarget == 0.0){
            flyPID.disable();
            //flyPID.reset();
            //flyPID.free();
        }
    }

    // Called when another command which requires one or more of the same
    // subsystems is scheduled to run
    protected void interrupted() {
        flyPID.setSetpoint(0.0);
        SmartDashboard.putDouble("targetRPM = ", usertarget);
        flyPID.disable();
        flyPID.zerohall();
        flyPID.zerospeed();
        //flyPID.reset();
        //flyPID.free();
        System.out.println("FLYPID Interupted");
        end();
    }

    public void readtablespeed() {
        //get the string value from the SmartDashboard and convert it to a double:
        double target = Double.parseDouble(preferencesTable.getString("Enter Flyrate then TAB key", "Empty"));
        usertarget = target;
        SmartDashboard.putDouble("targetRPM = ", usertarget);
    }
}
